﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using EasyNet.Solr;
using EasyNet.Solr.Commons;
using System.Collections;
using KernelClass;

namespace SolrExample.Tests.EasyNetSolr
{
    public class SolrObjectSerializer : IObjectSerializer<SolrIndexRecord> {
        public IEnumerable<SolrInputDocument> Serialize(IEnumerable<SolrIndexRecord> objs)
        {
            if (objs == null)
            {
                yield return null;
            }

            foreach (var obj in objs)
            {
                var doc = new SolrInputDocument();

                doc.Add("id", new SolrInputField("id", obj.Id));
                doc.Add("name", new SolrInputField("name", obj.Name));
                doc.Add("name_py", new SolrInputField("name_py", ChineseSpell.MakeSpellCode(obj.Name, "", SpellOptions.EnableUnicodeLetter)));
                doc.Add("tag", new SolrInputField("tag", obj.Tag));
                doc.Add("createdtime", new SolrInputField("createdtime", obj.CreatedTime));
                doc.Add("updatedtime", new SolrInputField("updatedtime", obj.UpdatedTime));

                yield return doc;
            }
        }
    }

    public class SolrObjectDeSerializer : IObjectDeserializer<SolrSearchResultRecord>
    {
        public string GetString(SolrDocument doc, string name)
        {
            if (!doc.ContainsKey(name))
            {
                return string.Empty;
            }
            var docObject = doc[name];
            if (docObject == null)
            {
                return string.Empty;
            }
            return docObject.ToString();

        }

        public IEnumerable<SolrSearchResultRecord> Deserialize(SolrDocumentList result)
        {
            if (result == null)
            {
                yield return null;
            }

            foreach (SolrDocument doc in result)
            {
                var record = new SolrSearchResultRecord();
                if (doc.ContainsKey("id"))
                {
                    record.Id = Convert.ToInt64(GetString(doc, "id"));
                }
                record.Name = GetString(doc, "name");
                if (doc.ContainsKey("tag"))
                {
                    var array = (ArrayList)doc["tag"];

                    if (array != null)
                    {
                        record.Tag = new string[array.Count];

                        for (var i = 0; i < array.Count; i++)
                        {
                            record.Tag[i] = array[i].ToString();
                        }
                    }
                }
                
                yield return record;
            }
        }
    }


}
